import re
import json
from common.handle import Handle
from common.utils import remove
from staffInfo.getStaffData import update, root_path
from staffInfo.department.dep_search import dep_search
from albertv0 import *


class Main(Handle):
    UPDATE_TRIGGER = 'update'
    UPDATE_REAL_TRIGGER = 'update_staff'

    @classmethod
    def handle_query(cls, query_model):
        query_str = query_model.query_str
        rs = cls.update(query_str)
        if rs is not None:
            return rs
        rs = cls.help(query_str)
        if rs is not None:
            return rs
        query_arr = query_str.split(' ')
        if len(query_arr) > 1 and (query_arr[0] == 'd' or query_arr[0] == '-d'):
            # 单独查询部门
            return dep_search(query_arr[1])
        dep_rs = dep_search(query_str)
        staff_rs = cls.search_staff(query_str)
        staff_rs = staff_rs if isinstance(staff_rs, list) else [staff_rs]
        return staff_rs + dep_rs
        pass

    @classmethod
    def search_staff(cls, query_str):
        k = cls.pretreatment(query_str)
        if k == 5:
            return {
                'text': '请确认搜索关键字的格式',
                'subtext': '无法执行搜索',
            }
        index = ['StaffNo', 'StaffID', 'UserID', 'Pinyin', 'StaffName']
        k = index[k]
        rs = cls.search(query_str, k)
        return rs
        pass

    @classmethod
    def update(cls, query_str):
        query_str = query_str.lower()
        # 按空格分隔
        query_arr = remove(query_str.split(' '))
        # 检测更新
        if len(query_arr) == 1 and query_arr[0] == cls.UPDATE_TRIGGER:
            return {
                'text': '请输入已经登录OM的cookie',
                'subtext': '输入cookie 用空格隔开',
                'completion': '4399 update ',
                'actions': [
                    # TermAction(text="TermAction",
                    #            commandline=["sleep", "5"],
                    #            cwd="~")
                ]
            }

        # trigger update
        if len(query_arr) > 1 and query_arr[0] == cls.UPDATE_TRIGGER:
            # join the query str
            _query_str = '4399 ' + cls.UPDATE_REAL_TRIGGER + ' ' + query_arr[1]
            return {
                'text': '按tab键更新数据',
                'subtext': '更新线上数据',
                'completion': _query_str,
            }

        # update
        if len(query_arr) > 1 and query_arr[0] == cls.UPDATE_REAL_TRIGGER:
            # update from on-line
            try:
                update(query_arr[1])
            except Exception as e:
                info(str(e))
                return {
                    'text': '更新失败 请确认cookie是否有效',
                    'subtext': '按tab重新进入更新',
                    'completion': '4399 update ',
                }
                pass
            return {
                'text': 'update complete...',
                'subtext': 'press tab if you want to query again',
                'completion': '4399 ',
            }

        return None
        pass

    @classmethod
    def search(cls, key, index):
        rs = []
        staff_info_path = root_path + "/staffInfo.json"
        with open(staff_info_path) as json_file:
            data = json.load(json_file)
        pattern = re.compile(key, re.I)
        d = {}
        for i in range(len(data)):
            if data[i][index] is None:
                continue
            if data[i][index].strip() == '':
                continue
            match = pattern.match(data[i][index])
            if match is not None:
                d = data[i]
                d['StaffName'] = '' if d['StaffName'] is None else d['StaffName']
                d['StaffID'] = '' if d['StaffID'] is None else d['StaffID']
                d['StaffNo'] = '' if d['StaffNo'] is None else d['StaffNo']
                # d['UserID'] = '' if d['UserID'] is None else d['UserID']
                tmp = {
                    'text': d['StaffName'],
                    'subtext': d['StaffID'] + " | " + d['StaffNo'],
                    'completion': '4399 ' + d['StaffID'],
                }
                rs.append(tmp)
                pass
            if index == 'Pinyin':
                if data[i]['Abbreviation'] is None:
                    continue
                if data[i]['Abbreviation'].strip() == '':
                    continue
                match = pattern.match(data[i]['Abbreviation'])
                if match is not None:
                    d = data[i]
                    d['StaffName'] = '' if d['StaffName'] is None else d['StaffName']
                    d['StaffID'] = '' if d['StaffID'] is None else d['StaffID']
                    d['StaffNo'] = '' if d['StaffNo'] is None else d['StaffNo']
                    # d['UserID'] = '' if d['UserID'] is None else d['UserID']
                    tmp = {
                        'text': d['StaffName'],
                        'subtext': d['StaffID'] + " | " + d['StaffNo'],
                    }
                    rs.append(tmp)
                    pass
                pass
        if len(rs) == 1:
            tmp = []
            for (k, v) in d.items():
                if k == 'Status':
                    continue
                t = {
                    'text': v,
                    'subtext': k,
                    'actions': [
                        ClipAction(text="ClipAction", clipboardText=v),
                    ]
                }
                tmp.append(t)
            rs = tmp
        return rs
        pass

    # 使用正则匹配工号 或 StaffID 或 UID
    @classmethod
    def pretreatment(cls, key):
        pattern = re.compile("^(gz|bj|xm){1}[0-9]{1,5}$", re.I)
        match = pattern.match(key)
        if match is not None:
            return 0
        pattern = re.compile('^s[0-9]{1,5}$', re.I)
        match = pattern.match(key)
        if match is not None:
            return 1
        pattern = re.compile('^u[0-9]{1,5}$', re.I)

        if match is not None:
            return 2
        # 拼音
        pattern = re.compile('^[a-z]{1,}$', re.I)
        match = pattern.match(key)
        if match is not None:
            return 3
        # 中文字符
        pattern = re.compile('^[\u4e00-\u9fa5]{1,}$', re.I)
        match = pattern.match(key)
        if match is not None:
            return 4
        return 5

    @classmethod
    def help(cls, query_str):
        if query_str == '-h' or query_str == '-help':
            return [
                {
                    'text': '按tab键展示查询demo',
                    'subtext': 'press tab',
                    'completion': '4399 GZ1133',
                },
                {
                    'text': '按tab键展示更新数据',
                    'subtext': 'press tab',
                    'completion': '4399 update 这里替换成已经登录成功的cookie',
                },
            ]
            pass
        return None
        pass

    pass
